package com.kfm.goods.controller;

import com.kfm.goods.bean.IPInfo;
import com.kfm.goods.domain.User;
import com.kfm.goods.ex.ServiceException;
import com.kfm.goods.service.UserService;
import com.kfm.goods.util.Constant;
import com.kfm.goods.util.IpUtil;
import com.wf.captcha.utils.CaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@CrossOrigin // 允许跨域
public class LoginController {
    @Autowired
    private UserService userService;

    @Autowired
    private IPInfo ipInfo;

    @GetMapping({"/", "/login"})
    public ModelAndView loginPage(){
        return new ModelAndView("login");
    }

    @GetMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        com.wf.captcha.utils.CaptchaUtil.out(request, response);
    }

    @PostMapping("/login")
    public ModelAndView doLogin(User user, String captcha, HttpServletRequest request, RedirectAttributes redirectAttributes){
        ModelAndView mv = new ModelAndView("redirect:/login");
        // 校验验证码
        if (!CaptchaUtil.ver(captcha, request)) {
            // 清除session中的验证码
            CaptchaUtil.clear(request);
            // 验证码错误
            redirectAttributes.addFlashAttribute("message", "验证码错误");
            return mv;
        }
        // 清除session中的验证码
        CaptchaUtil.clear(request);
        // 获取请求的 ip
        String ip = IpUtil.getIpAddress(request);
        try {
            // 登录操作
            User login = userService.login(user);

            // 清除错误次数
            ipInfo.getIpMap().remove(ip);

            // 登录成功
            request.getSession().setAttribute(Constant.LOGIN_USER, login);
            // 重定向到首页
            mv.setViewName("redirect:/index");
            return mv;
        } catch (ServiceException e) {
            e.printStackTrace();
            if (e.getCode() == Constant.USERNAME_PASSWORD_ERROR_CODE){
                // 用户名密码错误

                ipInfo.getIpMap().put(ip, ipInfo.getIpMap().getOrDefault(ip, 0) + 1);
            }
            redirectAttributes.addFlashAttribute("message", e.getMessage());
            return mv;
        }
    }


    @GetMapping("/index")
    public ModelAndView index(){
        return new ModelAndView("index");
    }


    @GetMapping("/element")
    public ModelAndView element(){
        return new ModelAndView("element");
    }


    @PostMapping("/json")
    public User json(@RequestBody User user){
        return new User();
    }
}
